package com.watson.httpsdemo.config;

import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.coyote.http11.Http11NioProtocol;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class BeanConfig {
    private final static Logger logger = LoggerFactory.getLogger(BeanConfig.class);
    @Bean
    public Connector createSslConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();

        ClassPathResource resource = new ClassPathResource("https.keystore");
        // 临时目录
        String tempPath =System.getProperty("java.io.tmpdir") + System.currentTimeMillis()+".keystore";
        File f = new File(tempPath);
        logger.info(".keystore目录临时存储路径" + tempPath);

        try {
            // 将key的值转存到临时文件
            IOUtils.copy(resource.getInputStream(),new FileOutputStream(f));
            connector.setScheme("https");
            connector.setSecure(true);
            connector.setPort(8099);
            protocol.setSSLEnabled(true);
            // 指向临时文件
            protocol.setKeystoreFile(f.getAbsolutePath());
            protocol.setKeystorePass("123456");
            protocol.setKeyAlias("https");
            protocol.setKeyPass("123456");
        } catch (IOException e) {
            e.printStackTrace();
        }

        return connector;
    }

    @Bean
    public TomcatServletWebServerFactory tomcatServletWebServerFactory(Connector connector){
        TomcatServletWebServerFactory tomcat=new TomcatServletWebServerFactory(){
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint securityConstraint=new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection=new SecurityCollection();
                collection.addPattern("/*");
                securityConstraint.addCollection(collection);
                context.addConstraint(securityConstraint);
            }
        };
        tomcat.addAdditionalTomcatConnectors(connector);
        return tomcat;
    }
}
